import client from '@/graphql/client';
import gql from 'graphql-tag';
import { listSchoolUsers } from '@/graphql/mutations';
import { getUserInfo, getUserInfoAdmin } from '@/graphql/queries';

export interface UserType {
  name: string;
  role: number;
  info: UserInfoType;
}

interface UserInfoType {
  schoolName?: string;
  schoolAddress?: string;
  schoolDetail?: string;
  headmaster?: string;
  phoneNumber?: string;
  identity?: string;
  subject?: string;
}
const loginInfo: any = JSON.parse(localStorage.getItem('userInfo') as any);
const userRole = loginInfo?.userRoles[0];

export default {
  namespace: 'user',
  //  !! 重要  不能删除 备用参考的mock数据
  // state: {
  //   name: '常孟云',
  //   role: 1,
  //   info: {
  //     schoolName: '上海外国语实验中学',
  //     schoolAddress: '上海市宝山区',
  //     schoolDetail:
  //       '场面和气氛描写为文章增色不少，对精彩地方进行简单描述，点面结合，简单介绍情况。自然过渡到下一段，情境描写调动起悬念，充分运用语言,动作,心理描写,使事情具描写,使事情具情具具体生动。进行简单描述，点面结合，简单介绍情况。自然过渡到下一段，情境描写调动起悬念，充分运用语言,动作,心理描写,使事情具',
  //     headmaster: '李天奇',
  //     phoneNumber: '18767758888',
  //     identity: '老师',
  //     subject: '语文',
  //   },
  // },
  state: {
    name: loginInfo?.name,
    role: loginInfo?.userRoles[0]?.role?.type,
    info: {
      schoolName: null,
      schoolAddress: '上海市宝山区',
      schoolDetail: null,
      headmaster: '李天奇',
      phoneNumber: null,
      identity: '老师',
      subject: null,
    },
  },
  reducers: {
    setUserInfo(state: UserType, { payload }) {
      // console.log(payload);
      const tmp = {
        ...state,
        ...payload,
      };
      console.log('tmp', tmp);

      return {
        ...state,
        ...payload,
      };
    },
  },
  effects: {
    *fetchAll({}: any, { select, put, call }: any): Generator<any, any, any> {
      // client.mutate({
      //   mutation: listSchoolUsers,
      //   variables: {
      //     type: 'User',
      //     organ_id: 'T3JnYW46Mg==',
      //     expand_organ_user: true,
      //     role_id: 'Um9sZTo0',
      //     name: 't',
      //     // type: loginInfo.__typename,
      //     // organ_id: userRole.organ_id,
      //     // expand_organ_user: true,
      //     // role_id: userRole.role_id,
      //     // name: loginInfo.name,
      //   },
      // }),
      try {
        const info = yield select((state: any) => state.user.info); // state + namespace

        const data = yield call(client.query, {
          query: getUserInfo,
        });
        const resData = data.data.getSessionUser;
        // console.log('resData', resData);
        const { organs, phone } = resData;
        let subject = ''; // 所属科目
        let schoolName = ''; // 所属学校名
        organs.forEach((item: any) => {
          console.log(item);
          item.subjects.forEach((i: any) => (subject += `, ${i.name}`));
          schoolName += ',' + item.parentOrgan.parentOrgan.name;
          localStorage.setItem('schoolId', item.parentOrgan.parentOrgan.id);
        });

        const payloadData = {
          info: {
            ...info,
            phoneNumber: phone,
            subject: subject.slice(1), // 这样子更简单 因为开始便利的时候再最前面加了个逗号
            schoolName: schoolName.slice(1),
          },
        };

        // console.log(payloadData, subject);

        yield put({ type: 'setUserInfo', payload: payloadData });
      } catch (error) {}

      // const data = yield call(getAllModule);
      // console.log(data.result);
      // yield put({ type: 'resetModuleList', payload: data.result });
    },
    *fetchAdminAll({}: any, { select, put, call }: any): Generator<any, any, any> {
      try {
        const info = yield select((state: any) => state.user.info); // state + namespace

        const data = yield call(client.query, {
          query: getUserInfoAdmin,
        });
        const resData = data.data.getSessionUser;
        console.log('resData', resData);
        const { organs, phone } = resData;
        let schoolName = ''; // 所属学校名
        let schoolDetail = ''; // 学校细节描述
        const organ = organs[0];
        console.log(organ);
        schoolName = organ.description;
        schoolDetail = organ.description;

        const payloadData = {
          info: {
            ...info,
            phoneNumber: phone,
            // subject: subject.slice(1), // 这样子更简单 因为开始便利的时候再最前面加了个逗号
            schoolDetail,
            schoolName: schoolName.slice(1),
          },
        };

        yield put({ type: 'setUserInfo', payload: payloadData });
      } catch (error) {}
    },
  },
  subscriptions: {
    setup({ dispatch, history }: { dispatch: any; history: any }) {
      const activate = () => {
        const role = userRole?.role?.type;
        // console.log('userRole', role, userRole);
        if (role === 1) {
          dispatch({ type: 'fetchAdminAll' });
        } else if (role === 3) {
          dispatch({ type: 'fetchAll' });
        }
      };
      return history.listen(({ pathname }: { pathname: string }) => {
        if (pathname.includes('personalCenter')) {
          activate();
        }
      });
    },
  },
};
